package com.bw.controller;

import cn.hutool.crypto.digest.DigestUtil;
import com.bw.domain.SysGoods;
import com.bw.log.Log;
import com.bw.service.SysGoodsService;
import com.bw.upload.FileUploadService;
import com.bw.utils.common.Result;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author bobo棒
 * @date 2024年03月08日 11:21
 */
@RequestMapping("goods")
@RestController
public class GoodsController {
    @Autowired
    SysGoodsService sysGoodsService;
    @Autowired
    RedisTemplate redisTemplate;

    @Log
    @RequestMapping("list")
    public Result list(@RequestBody(required = false) SysGoods sysGoods, @RequestParam(defaultValue = "1") Integer pageNum) {
        PageHelper.startPage(pageNum, 3);
        List<SysGoods> list = sysGoodsService.listGoods(sysGoods);
        PageInfo<SysGoods> info = new PageInfo<>(list);
        return Result.success(info);
    }




    @RequestMapping("add")
    public Result add(@RequestBody SysGoods sysGoods){
        //防止表单重复提交
        String key = DigestUtil.md5Hex(sysGoods.toString());
        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(key, 1, 1, TimeUnit.MINUTES);
        if(aBoolean){
            boolean b = sysGoodsService.saveGoods(sysGoods);
            return b?Result.success():Result.fail();
        }
        return Result.fail("请勿重复提交");



    }

    @Autowired
    FileUploadService fileUploadService;

    @RequestMapping("upFile")
    public Result upFile(MultipartFile file) throws IOException {
        String s = fileUploadService.uploadFile(file);
        return Result.success(s);
    }

}
